package com.itheima.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.dao.UserMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public User loadUserByUsername(String username) {
        //根据用户名查询用户信息（id，密码）
        User user = userMapper.findByUserName(username);
        if(null != user){
            //根据id查询用户的权限集合
                //1、根据用户id查询用户所有的角色
                Set<Role> roles = roleMapper.findByUserId(user.getId());
                if(CollectionUtil.isNotEmpty(roles)){
                    //2、循环角色集合查询角色对应的权限集合
                    for (Role role : roles) {
                        Set<Permission> permissions = permissionMapper.findByRoleId(role.getId());
                        role.setPermissions(permissions);
                    }
                }
                user.setRoles(roles);
        }
        return user;
    }
}
